package com.vtuzx.kingdee.xqc_api.service.impl;


import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.mongodb.internal.operation.CreateCollectionOperation;
import com.vtuzx.core.VtuzxException;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.vtuzx.core.bean.dto.VtuzxPage;
import com.vtuzx.core.bean.dto.VtuzxToken;
import com.vtuzx.core.constant.IVtuzxConst;
import com.vtuzx.core.constant.IVtuzxEnum;
import com.vtuzx.core.file.excel.VtuzxExcel;
import com.vtuzx.core.file.excel.VtuzxExcelCell;
import com.vtuzx.core.file.excel.VtuzxExcelRow;
import com.vtuzx.core.file.excel.VtuzxExcelSheet;
import com.vtuzx.core.utils.VtuzxUtil;
import com.vtuzx.fast.utils.FastUtil;
import com.vtuzx.kingdee.xqc_api.service.IXqcPurOrderService;
import com.vtuzx.kingdee.xqc_core.bean.VtuzxArrayList;
import com.vtuzx.kingdee.xqc_core.bean.kingdee.VtuzxKingdeeCloudClient;
import com.vtuzx.kingdee.xqc_core.constant.BillStatus;
import com.vtuzx.kingdee.xqc_core.constant.BillType;
import com.vtuzx.kingdee.xqc_core.constant.ConfigType;
import com.vtuzx.kingdee.xqc_core.dao.*;
import com.vtuzx.kingdee.xqc_core.service.IVtuzxBasicService;
import com.vtuzx.kingdee.xqc_core.service.IVtuzxKingdeeService;
import com.vtuzx.web.bean.VtuzxDownloadBean;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import javax.print.Doc;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 采购订单
 */
@Service
public class XqcPurOrderServiceImpl implements IXqcPurOrderService {

    /** Logger */
    private static final Logger _logger = LoggerFactory.getLogger(XqcPurOrderServiceImpl.class);

    @Autowired
    private SupplierDao supplierDao;

    @Autowired
    private PurContractDetailDao purContractDetailDao;

    @Autowired
    private PurOrderDao purOrderDao;

    @Autowired
    private PurOrderDetailDao purOrderDetailDao;

    @Autowired
    private PurSettlementDao purSettlementDao;

    /** 账号信息 */
    @Autowired
    private StoreTokenDao storeTokenDao;

    @Autowired
    private IVtuzxBasicService basicService;

    @Autowired
    private PurInSettlementDao purInSettlementDao;

    @Autowired
    private IVtuzxKingdeeService kingdeeService;

    @Override
    public void savePurOrder(ObjectId _userId, String name, Map<String, Object> param) {
        Map<String, Object> purOrderMap = new HashMap<>(param);
        String orderNo = VtuzxUtil.getString(purOrderMap, "orderNo");
        String purchaseDate = VtuzxUtil.getString(purOrderMap, "purchaseDate");
        List<Map<String, Object>> dataList = VtuzxUtil.getObject(purOrderMap, "dataList");
        purOrderDao.updateOne(Criteria.where("orderNo").is(orderNo), new Document("purchaseDate", purchaseDate));
        List<ObjectId> _idList = new ArrayList<>();
        for(Map<String, Object> data: dataList) {
            Document doc = new Document();
            doc.append("billNo", VtuzxUtil.getObject(data, "billNo"));
            doc.append("orderNo", VtuzxUtil.getObject(data, "orderNo"));
            doc.append("materialNo", VtuzxUtil.getObject(data, "materialNo"));
            doc.append("materialName", VtuzxUtil.getObject(data, "materialName"));
            doc.append("materialSpec", VtuzxUtil.getObject(data, "materialSpec"));
            doc.append("purchaseUnitName", VtuzxUtil.getObject(data, "purchaseUnitName"));
            doc.append("calcUnitName", VtuzxUtil.getObject(data, "calcUnitName"));
            doc.append("batchNo", VtuzxUtil.getObject(data, "batchNo"));
            doc.append("deliveryDate", VtuzxUtil.parseDate(VtuzxUtil.getObject(data, "deliveryDate")));
            doc.append("taxRateStr", VtuzxUtil.getObject(data, "taxRateStr"));
            doc.append("taxRate", VtuzxUtil.getObject(data, "taxRate"));
            doc.append("qty", VtuzxUtil.getObject(data, "qty"));
            doc.append("price", VtuzxUtil.getObject(data, "price"));
            doc.append("amount", VtuzxUtil.getObject(data, "amount"));
            doc.append("discountRate", VtuzxUtil.getObject(data, "discountRate"));
            doc.append("taxPrice", VtuzxUtil.getObject(data, "taxPrice"));
            doc.append("taxAmount", VtuzxUtil.getObject(data, "taxAmount"));
            doc.append("tax", VtuzxUtil.getObject(data, "tax"));
            doc.append("isGift", VtuzxUtil.getObject(data, "isGift"));

            String id = VtuzxUtil.getString(data, "id");
            if (VtuzxUtil.isEmpty(id)) {
                ObjectId _insId = purOrderDetailDao.insert(_userId, name, doc);
                _idList.add(_insId);
            } else {
                ObjectId _updId = FastUtil.convertId(id);
                purOrderDetailDao.update(_updId, _userId, name, doc);
                _idList.add(_updId);
            }
        }
        purOrderDetailDao.deleteMany(Criteria.where("orderNo").is(orderNo).and(IVtuzxConst.Key__id).nin(_idList));
        purSettlementDao.deleteMany(Criteria.where("orderNo").is(orderNo).and("_detailId").nin(_idList));
    }

    @Override
    public void deletePurOrder(ObjectId _userId, String name, Map<String, Object> param) {
        String orderNo = VtuzxUtil.getString(param, "orderNo");
        purOrderDao.deleteOne(Criteria.where("orderNo").is(orderNo));
        purOrderDetailDao.deleteMany(Criteria.where("orderNo").is(orderNo));
        purSettlementDao.deleteMany(Criteria.where("orderNo").is(orderNo));
    }

    @Override
    public void auditPurOrder(ObjectId _userId, String userName, String orderNo) throws VtuzxException {
        Criteria cond = Criteria.where("orderNo").is(orderNo).and("status").is(BillStatus.Save.toString());
        Document updateDoc = new Document("status", BillStatus.Audit.toString());
        updateDoc.append("_auditUserId", _userId);
        updateDoc.append("auditUserName", userName);
        updateDoc.append("auditTime", new Date());
        UpdateResult res = purOrderDao.updateOne(cond, updateDoc);
        if (res.getModifiedCount() == 0) {
            throw new VtuzxException(IVtuzxConst.Msg_E_target_not_exist);
        }
    }

    @Override
    public void unAuditPurOrder(ObjectId _userId, String name, String orderNo) throws VtuzxException {
        long orderCount = purOrderDao.count(Criteria.where("DDBillNo").is(orderNo));
        if (orderCount > 0) {
            throw new VtuzxException("存在下游单据, 不能反审!");
        }
        Criteria cond = Criteria.where("orderNo").is(orderNo).and("status").is(BillStatus.Audit.toString());
        Document setDoc = new Document("status", BillStatus.Save.toString());
        Document unsetDoc = new Document("_auditUserId", 1);
        unsetDoc.append("auditUserName", 1);
        unsetDoc.append("auditTime", 1);
        UpdateResult res = purOrderDao.updateOneRedirect(cond, new Document("$set", setDoc).append("$unset", unsetDoc));
        if (res.getModifiedCount() == 0) {
            throw new VtuzxException(IVtuzxConst.Msg_E_target_not_exist);
        }
    }

    @Override
    public VtuzxMap getPurOrderList(ObjectId _userId, Map<String, Object> param, int pageIndex, int pageSize) {
        Criteria cond = getPurOrderListCond(param);
        if (cond == null) {
            return new VtuzxMap();
        }
        VtuzxPage page = purOrderDao.page(cond, new Document("createTime", -1), pageIndex, pageSize);
        List<VtuzxMap> dataList = page.iterator(doc -> {
            VtuzxMap data = new VtuzxMap(doc);
            data.append(IVtuzxConst.Key_createTime, VtuzxUtil.formatYmdHmF(VtuzxUtil.removeObject(data, IVtuzxConst.Key_createTime)));
            data.append("auditTime", VtuzxUtil.formatYmdHmF(VtuzxUtil.removeObject(data, "auditTime")));
            data.remove(IVtuzxConst.Key_updateTime);
            data.remove("_createUserId");
            data.remove("_updateUserId");
            data.remove("_auditUserId");
            return data;
        });
        return new VtuzxMap(IVtuzxConst.Key_total, page.total()).append(IVtuzxConst.Key_data, dataList);
    }

    @Override
    public VtuzxMap getPurOrder(ObjectId userId, String name, String orderNo) throws VtuzxException {
        Document orderDoc = purOrderDao.findOne(Criteria.where("orderNo").is(orderNo));
        if (orderDoc == null) {
            throw new VtuzxException(IVtuzxConst.Msg_E_target_not_exist);
        }
        VtuzxMap header = new VtuzxMap();
        header.append("orderNo", orderNo);
        header.append("billNo", VtuzxUtil.getString(orderDoc, "billNo"));
        header.append("orderType", VtuzxUtil.getString(orderDoc, "orderType"));
        header.append("purchaseDept", VtuzxUtil.getString(orderDoc, "purchaseDept"));
        header.append("purchaseDeptName", VtuzxUtil.getString(orderDoc, "purchaseDeptName"));
        header.append("purchaser", VtuzxUtil.getString(orderDoc, "purchaser"));
        header.append("purchaserName", VtuzxUtil.getString(orderDoc, "purchaserName"));
        header.append("supplierNo", VtuzxUtil.getString(orderDoc, "supplierNo"));
        header.append("supplierName", VtuzxUtil.getString(orderDoc, "supplierName"));
        header.append("charge", VtuzxUtil.getString(orderDoc, "charge"));
        header.append("settle", VtuzxUtil.getString(orderDoc, "settle"));
        header.append("remark", VtuzxUtil.getString(orderDoc, "remark"));
        header.append("purchaseDate", VtuzxUtil.getString(orderDoc, "purchaseDate"));
        header.append("status", VtuzxUtil.getString(orderDoc, "status"));

        List<VtuzxMap> dataList = new ArrayList<>();
        Iterator<Document> orderDetailItr = purOrderDetailDao.findList(Criteria.where("orderNo").is(orderNo), new Document(IVtuzxConst.Key__id, 1), 0, 0);
        while (orderDetailItr.hasNext()) {
            Document doc = orderDetailItr.next();
            VtuzxMap detail = new VtuzxMap(doc);
            detail.append("id", VtuzxUtil.removeString(detail, IVtuzxConst.Key__id));
            detail.append("deliveryDate", VtuzxUtil.formatYmdF(VtuzxUtil.removeObject(doc, "deliveryDate")));
            detail.remove("_createUserId");
            detail.remove("createUserName");
            detail.remove("_updateUserId");
            detail.remove("updateUserName");
            detail.remove(IVtuzxConst.Key_createTime);
            detail.remove(IVtuzxConst.Key_updateTime);
            dataList.add(detail);
        }
        return new VtuzxMap("header", header).append(IVtuzxConst.Key_data, dataList);
    }

    @Override
    public VtuzxDownloadBean downloadPurOrder(VtuzxToken token, Map<String, Object> param) throws Exception {
        Criteria cond = getPurOrderListCond(param);
        List<VtuzxMap> dataList = new ArrayList<>();
        if (cond != null) {
            Iterator<Document> purOrderItr = purOrderDao.findPurOrderList(cond);
            while (purOrderItr.hasNext()) {
                Document doc = purOrderItr.next();
                VtuzxMap data = new VtuzxMap(doc);
                Document detail = VtuzxUtil.getObject(data, "detail");
                if (detail != null) {
                    data.putAll(detail);
                    String isGift = VtuzxUtil.getString(data, "isGift", "0");
                    data.append("isGift", isGift.equals("0")? "否": "是");
                    data.append("deliveryDate", VtuzxUtil.formatYmdF(VtuzxUtil.getObject(data, "deliveryDate")));
                }
                Document settlement = VtuzxUtil.getObject(data, "settlement");
                if (settlement != null) {
                    data.append("s.settlementQty", VtuzxUtil.getObject(settlement, "settlementQty"));
                    data.append("s.settlementCount", VtuzxUtil.getObject(settlement, "settlementCount"));
                    data.append("s.settlementAmount", VtuzxUtil.getObject(settlement, "settlementAmount"));
                    Date auditTime = VtuzxUtil.getObject(settlement, "auditTime");
                    if (auditTime != null) {
                        data.append("s.settlementAuditTime", VtuzxUtil.formatYmdHmF(auditTime));
                    }
                }
                dataList.add(data);
            }
        }

        String timestamp = new SimpleDateFormat("yyMMddHHmmss").format(new Date());

        List<VtuzxExcelSheet> sheets = new ArrayList<>();
        VtuzxExcelSheet sheet0 = new VtuzxExcelSheet(0, "采购订单");
        int col = 0;
        int row = 0;
        VtuzxExcelRow header0 = new VtuzxExcelRow(row++, new VtuzxArrayList<>(
                new VtuzxExcelCell(col++, "单据编号"),
                new VtuzxExcelCell(col++, "单据类型"),
                new VtuzxExcelCell(col++, "采购部门"),
                new VtuzxExcelCell(col++, "采购员"),
                new VtuzxExcelCell(col++, "采购日期"),
                new VtuzxExcelCell(col++, "供应商"),
                new VtuzxExcelCell(col++, "收款方"),
                new VtuzxExcelCell(col++, "结算方"),
                new VtuzxExcelCell(col++, "合同号"),
                new VtuzxExcelCell(col++, "物料编码"),
                new VtuzxExcelCell(col++, "物料名称"),
                new VtuzxExcelCell(col++, "规格型号"),
                new VtuzxExcelCell(col++, "采购单位"),
                new VtuzxExcelCell(col++, "采购数量"),
                new VtuzxExcelCell(col++, "计价单位"),
                new VtuzxExcelCell(col++, "交货日期"),
                new VtuzxExcelCell(col++, "单价"),
                new VtuzxExcelCell(col++, "含税单价"),
                new VtuzxExcelCell(col++, "折扣率"),
                new VtuzxExcelCell(col++, "金额"),
                new VtuzxExcelCell(col++, "税率"),
                new VtuzxExcelCell(col++, "税额"),
                new VtuzxExcelCell(col++, "价税合计"),
                new VtuzxExcelCell(col++, "是否赠品"),
                new VtuzxExcelCell(col++, "到货数量"),
                new VtuzxExcelCell(col++, "结算金额"),
                new VtuzxExcelCell(col++, "本次结算数量"),
                new VtuzxExcelCell(col++, "本次结算金额"),
                new VtuzxExcelCell(col, "时间")
        ));
        sheet0.addRow(header0);

        for (VtuzxMap data : dataList) {
            col = 0;
            VtuzxExcelRow dataRow = new VtuzxExcelRow(row++, new VtuzxArrayList<>(
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "orderNo")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "orderType")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "purchaseDeptName")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "purchaserName")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "purchaseDate")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "supplierName")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "charge")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "settle")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "billNo")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "materialNo")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "materialName")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "materialSpec")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "purchaseUnitName")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "qty")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "calcUnitName")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "deliveryDate")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "price")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "taxPrice")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "discountRate")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "amount")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "taxRateStr")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "tax")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "taxAmount")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "isGift")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "settlementQty")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "settlementAmount")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "s.settlementQty")),
                    new VtuzxExcelCell(col++, VtuzxUtil.getString(data, "s.settlementAmount")),
                    new VtuzxExcelCell(col, VtuzxUtil.getString(data, "s.settlementAuditTime"))
            ));
            sheet0.addRow(dataRow);
        }

        sheet0.setColumnWidth(new VtuzxArrayList<>(
                new int[]{0, 200},
                new int[]{1, 200},
                new int[]{2, 200},
                new int[]{3, 150},
                new int[]{4, 200},
                new int[]{5, 200},
                new int[]{6, 150},
                new int[]{7, 150},
                new int[]{8, 150},
                new int[]{9, 150},
                new int[]{10, 150},
                new int[]{11, 150},
                new int[]{12, 150},
                new int[]{13, 150},
                new int[]{14, 150},
                new int[]{15, 150},
                new int[]{16, 150},
                new int[]{17, 150},
                new int[]{18, 150},
                new int[]{19, 150},
                new int[]{20, 150},
                new int[]{21, 150},
                new int[]{22, 150},
                new int[]{23, 150},
                new int[]{24, 150},
                new int[]{25, 150},
                new int[]{26, 150},
                new int[]{27, 150},
                new int[]{28, 150},
                new int[]{29, 300}
        ));
        sheets.add(sheet0);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        VtuzxExcel.write(stream, sheets);
        return new VtuzxDownloadBean("采购订单" + timestamp + ".xlsx", stream);
    }

    @Override
    public VtuzxMap savePurOrderSettlement(ObjectId _userId, String name, Map<String, Object> param) {
        Document settlementDoc = new Document();
        settlementDoc.append("settlementQty", VtuzxUtil.getInt(param, "settlementQty"));
        settlementDoc.append("settlementAmount", VtuzxUtil.getDouble(param, "settlementAmount"));
        String id = VtuzxUtil.getString(param, "id");
        if (VtuzxUtil.isEmpty(id)) {
            settlementDoc.append("billNo", VtuzxUtil.getString(param, "billNo"));
            settlementDoc.append("orderNo", VtuzxUtil.getString(param, "orderNo"));
            settlementDoc.append("status", BillStatus.Save.toString());
            settlementDoc.append("_detailId", FastUtil.convertId(VtuzxUtil.getString(param, "detailId")));
            ObjectId _id = purSettlementDao.insert(_userId, name, settlementDoc);
            return new VtuzxMap("id", _id.toString());
        } else {
            purSettlementDao.update(_userId, name, id, settlementDoc);
            return new VtuzxMap("id", id);
        }
    }

    @Override
    public void deletePurOrderSettlement(List<String> ids) {
        Criteria cond = Criteria.where(IVtuzxConst.Key__id).is(FastUtil.convertId(ids));
        cond.and("status").is(BillStatus.Save.toString());
        purSettlementDao.deleteMany(cond);
    }

    @Override
    public void auditPurOrderSettlement(ObjectId _userId, String name, String id) throws VtuzxException {
        Document settlement = purSettlementDao.findById(id);
        if (settlement == null) {
            throw new VtuzxException(IVtuzxConst.Msg_E_target_not_exist);
        }
        purSettlementDao.audit(_userId, name, id);
        refreshSettlement(settlement);
    }

    @Override
    public void unAuditPurOrderSettlement(ObjectId userId, String name, String id) throws VtuzxException {
        Document settlement = purSettlementDao.findById(id);
        if (settlement == null) {
            throw new VtuzxException(IVtuzxConst.Msg_E_target_not_exist);
        }
        purSettlementDao.unaudit(id);
        refreshSettlement(settlement);
    }

    @Override
    public VtuzxMap getPurOrderSettlement(ObjectId userId, String name, Map<String, Object> param) {
        ObjectId _detailId = FastUtil.convertId(VtuzxUtil.getString(param, "detailId"));
        Iterator<Document> settlementItr = purSettlementDao.findList(Criteria.where("_detailId").is(_detailId), new Document("createTime", -1), 0, 0);
        List<VtuzxMap> settleList = new ArrayList<>();
        while (settlementItr.hasNext()) {
            Document doc = settlementItr.next();
            VtuzxMap data = new VtuzxMap();
            data.append("id",VtuzxUtil.getString(doc, IVtuzxConst.Key__id));
            data.append("status", VtuzxUtil.getObject(doc,"status"));
            data.append("settlementQty", VtuzxUtil.getObject(doc,"settlementQty"));
            data.append("settlementAmount", VtuzxUtil.getObject(doc,"settlementAmount"));
            data.append("auditUserName", VtuzxUtil.getString(doc,"auditUserName"));
            data.append("auditTime", VtuzxUtil.formatYmdHmF(VtuzxUtil.removeObject(doc, "auditTime")));
            data.append("createUserName", VtuzxUtil.getString(doc,"createUserName"));
            data.append(IVtuzxConst.Key_createTime, VtuzxUtil.formatYmdHmF(VtuzxUtil.removeObject(doc, IVtuzxConst.Key_createTime)));
            settleList.add(data);
        }
        return new VtuzxMap("data", settleList);
    }

    /**
     * 采购订单列表检索条件
     *
     * @param param 输入条件
     * @return 检索条件
     */
    private Criteria getPurOrderListCond(Map<String, Object> param) {
        String materialNo = VtuzxUtil.getString(param, "materialNo");
        Criteria cond = new Criteria();
        String orderType = VtuzxUtil.getString(param, "orderType");
        String billNo = VtuzxUtil.getString(param, "billNo");
        String supplierNo = VtuzxUtil.getString(param, "supplierNo");
        List<String> createTimeList = VtuzxUtil.getObject(param, "createTime");
        if (!VtuzxUtil.isEmpty(orderType)) {
            cond.and("orderType").regex(orderType);
        }
        if (!VtuzxUtil.isEmpty(billNo)) {
            cond.and("billNo").regex(billNo.trim());
        }
        if (!VtuzxUtil.isEmpty(supplierNo)) {
            cond.and("supplierNo").is(supplierNo.trim());
        }
        if (!VtuzxUtil.isEmpty(createTimeList)) {
            cond.and("createTime").gte(VtuzxUtil.parseDate(createTimeList.get(0))).lte(VtuzxUtil.parseDate(createTimeList.get(1) + " 23:59:59"));
        }
        if (!VtuzxUtil.isEmpty(materialNo)) {
            Iterator<Document> purOrderDetailItr = purOrderDetailDao.findList(Criteria.where("materialNo").is(materialNo), null, 0, 0);
            List<String> orderNoList = new ArrayList<>();
            while (purOrderDetailItr.hasNext()) {
                Document purOrderDetailDoc = purOrderDetailItr.next();
                String orderNo = VtuzxUtil.getString(purOrderDetailDoc, "orderNo");
                orderNoList.add(orderNo);
            }
            if (!VtuzxUtil.isEmpty(orderNoList)) {
                cond.and("orderNo").in(orderNoList);
            } else {
                return null;
            }
        } else {
            String orderNo = VtuzxUtil.getString(param, "orderNo");
            if (!VtuzxUtil.isEmpty(orderNo)) {
                cond.and("orderNo").regex(orderNo.trim());
            }
        }
        return cond;
    }

    /**
     * 刷新结算信息
     *
     * @param settlement 采购订单分录结算
     */
    //TODO
    private void refreshSettlement(Document settlement) {
        ObjectId _detailId = VtuzxUtil.getObject(settlement, "_detailId");
        Document detail = purOrderDetailDao.findById(_detailId);
        {
            // 订单分录结算信息重新计算
            Criteria cond = Criteria.where("_detailId").is(_detailId).and("status").is(BillStatus.Audit.toString());
            Iterator<Document> itr = purSettlementDao.findList(cond, null, 0, 0);
            int count = 0;
            double qty = 0d;
            double amount = 0d;
            while(itr.hasNext()) {
                Document doc = itr.next();
                count++;
                qty += VtuzxUtil.getDouble(doc, "settlementQty");
                amount += VtuzxUtil.getDouble(doc, "settlementAmount");
            }
            purOrderDetailDao.updateById(_detailId,
                    new Document("settlementQty", qty).append("settlementAmount", amount).append("settlementCount", count));
        }
        ObjectId _billDetailId = VtuzxUtil.getObject(detail, "_billDetailId");
        if (_billDetailId != null) {
            // 合同分录结算信息重新计算
            Criteria cond = Criteria.where("_billDetailId").is(_billDetailId);
            Iterator<Document> itr = purOrderDetailDao.findList(cond, null, 0, 0);
            int count = 0;
            double qty = 0d;
            double amount = 0d;
            while(itr.hasNext()) {
                Document doc = itr.next();
                count += VtuzxUtil.getDouble(doc, "settlementCount");
                qty += VtuzxUtil.getDouble(doc, "settlementQty");
                amount += VtuzxUtil.getDouble(doc, "settlementAmount");
            }
            purContractDetailDao.updateById(_billDetailId,
                    new Document("settlementQty", qty).append("settlementAmount", amount).append("settlementCount", count));
        }
    }

    @Override
    public void syncKingdeePurOrder(VtuzxToken token, Map<String, Object> param) throws Exception {
        Document storeToken = storeTokenDao.findOne(Criteria.where("type").is(ConfigType.Kingdee.toString()));
        ObjectId _storeId = VtuzxUtil.getObject(storeToken, IVtuzxConst.Key__id);
        storeTokenDao.updateById(_storeId, new Document("reloadPurOrder", true).append("reloadPurOrderStartTime", new Date()).append("reloadPurOrderRes", true).append("reloadPurOrderMsg", ""));
        try {
            basicService.syncPurOrder();
            storeTokenDao.updateById(_storeId, new Document("reloadPurOrder", false).append("reloadPurOrderEndTime", new Date()));
        } catch(Exception e) {
            _logger.info(e.getMessage());
            storeTokenDao.updateById(_storeId, new Document("reloadPurOrder", false).append("reloadPurOrderEndTime", new Date()).append("reloadPurOrderRes", false).append("reloadPurOrderMsg", e.getMessage()));
        }
    }

    @Override
    public VtuzxMap getKingdeePurOrder(VtuzxToken token, Map<String, Object> param) {
        Document storeToken = storeTokenDao.findOne(Criteria.where("type").is(ConfigType.Kingdee.toString()));
        return new VtuzxMap("reloadPurOrder", VtuzxUtil.getBoolean(storeToken, "reloadPurOrder"))
                .append("reloadPurOrderRes", VtuzxUtil.getBoolean(storeToken, "reloadPurOrderRes"))
                .append("reloadPurOrderMsg", VtuzxUtil.getString(storeToken, "reloadPurOrderMsg"))
                .append("reloadPurOrderStartTime", VtuzxUtil.formatYmdHmsF(VtuzxUtil.getObject(storeToken, "reloadPurOrderStartTime")))
                .append("reloadPurOrderEndTime", VtuzxUtil.formatYmdHmsF(VtuzxUtil.getObject(storeToken, "reloadPurOrderEndTime")));
    }
}
